package com.estar.assistsurvy.activity;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import org.apache.http.util.EncodingUtils;

import com.estar.assistsurvy.R;
import com.estar.assistsurvy.adapter.ChangeAddressDialog1;
import com.estar.assistsurvy.adapter.ChangeAddressDialog1.OnAddressCListener;
import com.estar.assistsurvy.entity.CityVO;
import com.estar.assistsurvy.entity.EsBankTopClass;
import com.estar.assistsurvy.entity.ProvinceVO;
import com.estar.assistsurvy.entity.RequestAreaInfo;
import com.estar.assistsurvy.entity.RequestBankClassInfo;
import com.estar.assistsurvy.entity.RequestSubmitBank;
import com.estar.assistsurvy.entity.ResponseAreaInfo;
import com.estar.assistsurvy.entity.ResponseBankClassInfo;
import com.estar.assistsurvy.entity.ResponseMsg;
import com.estar.assistsurvy.thread.AreaInfoThread;
import com.estar.assistsurvy.thread.BankTopClassInfoThread;
import com.estar.assistsurvy.thread.SubmitbankThread;
import com.estar.assistsurvy.utils.ExitUtils;
import com.estar.assistsurvy.utils.FileUtils;
import com.estar.assistsurvy.utils.MightypleUtil;
import com.estar.assistsurvy.widget.SelectBankPopwindow;
import com.google.gson.Gson;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.Resources.NotFoundException;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;

public class AddBankCardActivity extends BaseActivity implements OnClickListener{

	private LinearLayout returnBack;
	private EditText personName,cardNumber,cardType,cardProvince;
	private Button submit;
	private SharedPreferences prefer;
	private String deviceUUID;//	设备唯一标识
	private String uUID;//	用户唯一标识
	private String bankCardName;//持卡人姓名
	private String bankBranchCode="";//支行代码，可以为空
	private String bankBranchName="";//支行名称，可以为空
	private String bankCardNumber;//银行卡号
	private String areaCode="";//区代码，可以为空
	private String areaName="";//区名称，可以为空
	private String detailedAddress="";//详细地址（详细街道），可以为空
	private InputMethodManager imm;
	private List<EsBankTopClass>  bankTopClassList;
	private String bankIsValid="0";
	private EsBankTopClass bankClass;
	private List<ProvinceVO> areaList;
	private String json;
	private ProvinceVO province;
	private List<CityVO> cityList;
	private CityVO city;
//	private SelectAreaPopwindow areaPop;
	private SelectBankPopwindow bankPop;
	private static final String FILE_HOME=Environment.getExternalStorageDirectory()+File.separator+"areaAndBanks/";
	private Gson gson;
	private Handler handler=new Handler(){
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case -1:
				showShortToast((String) msg.obj);
				break;

			case 0:
				ResponseMsg message=new ResponseMsg();
				message=(ResponseMsg) msg.obj;
				showShortToast(message.getMessages());
				break;

			case 1:
				ResponseBankClassInfo bankInfo=new ResponseBankClassInfo();
				bankInfo=(ResponseBankClassInfo) msg.obj;
				if(bankInfo.getCode().equals("1")){
					bankTopClassList=bankInfo.getBankTopClassList();
					if(bankTopClassList.size()>0&&bankTopClassList!=null){
						bankIsValid="1";
					}else{
						showShortToast("当前银行列表为空!");
					}
				}else if(bankInfo.getCode().equals("0")){
					showShortToast(bankInfo.getMessages());
				}else if(bankInfo.getCode().equals("2")){
					ExitUtils.Unlogin(AddBankCardActivity.this, bankInfo.getMessages());
				}
				break;

			case 2:
				ResponseAreaInfo areaInfo=new ResponseAreaInfo();
				areaInfo=(ResponseAreaInfo) msg.obj;
				if(areaInfo.getCode().equals("1")){
					areaList=areaInfo.getAreaList();
					if(areaList!=null||areaList.size()>0){
					}else{
						showShortToast("当前地址列表为空!");
					}
				}else{
					showShortToast(areaInfo.getMessages());
				}
				break;
				
			case 3:
				String[] array=(String[]) msg.obj;
				String provinceName=array[0];
				String cityName=array[1];
				for(int i=0;i<areaList.size();i++){
					ProvinceVO provinceVO=areaList.get(i);
					if(provinceVO.getAreaName().equals(provinceName)){
						province=provinceVO;
						cityList=provinceVO.getCityList();
						for(int j=0;j<cityList.size();j++){
							CityVO cityVO=cityList.get(j);
							if(cityVO.getAreaName().equals(cityName)){
								city=cityVO;
								cardProvince.setText(province.getAreaName()+city.getAreaName());
							}
						}
					}
				}
				break;

			default:
				break;
			}
		};
	};
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_addbankcard);
		initView();
		initList();
	}

	private void initView(){
		returnBack=find(R.id.returnBack);
		returnBack.setOnClickListener(this);
		personName=find(R.id.personName);
		cardNumber=find(R.id.cardNumber);
		cardType=find(R.id.cardType);
		cardType.setOnClickListener(this);
		cardProvince=find(R.id.cardProvince);
		cardProvince.setOnClickListener(this);
		submit=find(R.id.submit);
		submit.setOnClickListener(this);

		prefer=getSharedPreferences("user", MODE_PRIVATE);
		uUID=prefer.getString("uuid", "");
		deviceUUID=MightypleUtil.getDeviceId(this);
		imm=(InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);

		gson=new Gson();
		File areaFile=new File(FILE_HOME, "areaList.txt");
		if(areaFile.exists()){
			ResponseAreaInfo areaInfo=new ResponseAreaInfo();
			String json;
			try {
				json = FileUtils.readFileSdcardFile(FILE_HOME+"areaList.txt");
//				json=json.replaceAll(" ", "");
				areaInfo=gson.fromJson(json, ResponseAreaInfo.class);
				areaList=areaInfo.getAreaList();
				if(areaList!=null||areaList.size()>0){
				}else{
					showShortToast("当前地址列表为空!");
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}else{
			RequestAreaInfo requestArea=new RequestAreaInfo(deviceUUID, uUID);
			new AreaInfoThread(this, handler, requestArea).start();
		}
		
		RequestBankClassInfo requestBank=new RequestBankClassInfo(deviceUUID, uUID);
		new BankTopClassInfoThread(this, handler, requestBank).start();
		
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.returnBack:
			finish();
			break;

		case R.id.cardType:
			imm.hideSoftInputFromWindow(v.getWindowToken(), 0); //强制隐藏键盘  
			if(bankIsValid.equals("1")){
				bankPop=new SelectBankPopwindow(AddBankCardActivity.this, "选择银行卡类型", new OnItemClickListener() {

					@Override
					public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
						// TODO Auto-generated method stub
						bankClass=bankTopClassList.get(position);
						cardType.setText((CharSequence) bankTopClassList.get(position).getBankTopClassName());
						bankPop.dismiss();
					}
				},bankTopClassList);
				// 设置optionPop显示的位置
				bankPop.showAtLocation(AddBankCardActivity.this
						.findViewById(R.id.submit), Gravity.CENTER
						| Gravity.CENTER_HORIZONTAL, 0, 0);
			}else{
				showShortToast("未获取到银行卡列表信息，请退出重试!");
			}
			break;

		case R.id.cardProvince:
			hideKeyboard();
//			imm.hideSoftInputFromWindow(v.getWindowToken(), 0); //强制隐藏键盘  
//			if(areaIsValid.equals("0")){
//				showShortToast("未获取到省市列表信息，请退出重试!");
//			}else{
//				areaPop=new SelectAreaPopwindow(AddBankCardActivity.this, new OnItemClickListener() {
//
//					@Override
//					public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//						// TODO Auto-generated method stub
//						areaPop.setCityList(position);
//						province=areaList.get(position);
////						cityList=areaList.get(position).getCityList();
//					}
//				}, new OnItemClickListener() {
//
//					@Override
//					public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//						// TODO Auto-generated method stub
//						city=province.getCityList().get(position);
//						cardProvince.setText(province.getAreaName()+city.getAreaName());
//						areaPop.dismiss();
//					}
//				}, areaList);
//				areaPop.showAtLocation(AddBankCardActivity.this
//						.findViewById(R.id.submit), Gravity.CENTER
//						| Gravity.CENTER_HORIZONTAL, 0, 0);
//			}
			ChangeAddressDialog1 mChangeAddressDialog = new ChangeAddressDialog1(
					AddBankCardActivity.this);
			mChangeAddressDialog.setAddress("北京市", "东城区");
			mChangeAddressDialog.show();
			mChangeAddressDialog
					.setAddresskListener(new OnAddressCListener() {

						@Override
						public void onClick(String province, String city) {
							// TODO Auto-generated method stub
//							Toast.makeText(MainActivity.this,
//									province + "-" + city,
//									Toast.LENGTH_LONG).show();
							Message msg=handler.obtainMessage();
							String[] array=new String[]{province,city};
							msg.what=3;
							msg.obj=array;
							msg.sendToTarget();
						}
					});
			break;

		case R.id.submit:
			bankCardName=personName.getText().toString().trim();
			bankCardNumber=cardNumber.getText().toString().trim();
			if(bankCardName.equals("")){
				showShortToast("持卡人不能为空!");
				return;
			}else if(bankCardNumber.length()==16||bankCardNumber.length()==19){
				if(bankClass==null){
					showShortToast("请选择银行类型!");
					return;
				}else{
					if(province==null||city==null){
						showShortToast("请选择开户行所在省市!");
						return;
					}else{
						RequestSubmitBank submitBank=new RequestSubmitBank(deviceUUID, uUID, bankCardName, bankClass.getBankTopClassCode(), bankClass.getBankTopClassName(), 
								bankBranchCode, bankBranchName, bankCardNumber, province.getAreaCode(), province.getAreaName(), 
								city.getAreaCode(), city.getAreaName(), areaCode, areaName, detailedAddress);
						new SubmitbankThread(this, handler, submitBank).start();
					}
				}
			}else{
				showShortToast("您输入的卡号不合法，请重试!");
				return;
			}
			break;

		default:
			break;
		}
	}
	
	private void initList(){
		try {
			InputStream input = getResources().openRawResource(R.raw.arealist);
			int length = input.available();

			byte [] buffer = new byte[length];   
			input.read(buffer);       

			json = EncodingUtils.getString(buffer, "UTF-8");   

			input.close();
			
			gson=new Gson();
			ResponseAreaInfo areaInfo=gson.fromJson(json, ResponseAreaInfo.class);
			areaList=areaInfo.getAreaList();
		} catch (NotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}  
		
	}
	
	// 隐藏软键盘
			private void hideKeyboard() {
				if (getWindow().getAttributes().softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) {
					if (getCurrentFocus() != null)
						imm.hideSoftInputFromWindow(getCurrentFocus()
								.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
				}
			}

}
